<template>
  <div class="departments" v-loading="loading">
    <el-card class="box-card">
      <!-- 第一行 -->
      <tree-tool :treeNode="company" :isRoot="true" @addDept="doadd" />

      <el-divider></el-divider>

      <el-tree
        :data="data"
        :props="defaultProps"
        node-key="id"
        default-expand-all
        :expand-on-click-node="false"
      >
        <!-- 把data传递给这个组件里的treeNode -->
        <tree-tool
          slot-scope="{ data }"
          :treeNode="data"
          @delDepartments="getChart"
          @addDept="doadd"
          @adddepartment="adddpt"
        />
      </el-tree>
      <addDeparts
        :pid="currentId"
        :showDialog.sync="showDialog"
        @doDept="getChart"
        ref="addDepts"
      />
    </el-card>
  </div>
</template>

<script>
// 导入组件
import treeTool from "./components/tree-tool";
import addDeparts from "./components/add-departs";
// 导入请求
import { getDepartments } from "@/api/departments.js";
// 导入递归工具函数
import { transTotreeData } from "@/utils";
export default {
  components: {
    treeTool,
    addDeparts,
  },
  data() {
    return {
      // 控制加载动画
      loading: true,
      currentId: "",
      showDialog: false,
      company: {
        name: "江苏传智播客教育科技股份有限公司",
        manager: "负责人",
      },
      // 绑定tree的默认显示文字和子节点
      defaultProps: {
        label: "name",
        children: "children",
      },
      data: [
        {
          id: 1,
          manager: "熊梦曦",
          name: "总裁办",
          children: [
            {
              id: 11,
              name: "教学办",
              manager: "张三",
            },
          ],
        },
        {
          id: 2,
          name: "行政部",
          manager: "李武",
        },
        {
          id: 3,
          name: "人事部",
          manager: "李四",
        },
      ],
    };
  },
  created() {
    // 调用请求
    this.getChart();
  },
  methods: {
    // 因为请求要多次使用所以封装到此处
    async getChart() {
      this.loading = true;
      let res = await getDepartments();
      // console.log(res);
      // 渲染公司名
      this.company.name = res.data.companyName;
      // 给一级菜单加点击事件传递一个id
      this.company.id = "";
      // 把结构单独拿出来处理
      let list = res.data.depts;
      // 优化递归
      this.data = transTotreeData(list, "");
      this.loading = false;
    },
    doadd(id) {
      this.currentId = id;
      this.showDialog = true;
    },
    // 查看部门部门编辑
    async adddpt(id) {
      // 调用请求
      await this.$refs.addDepts.getDetail(id);
      // 弹框
      this.showDialog = true;
    },
  },
};
</script>

<style>
.box-card {
  margin: 20px;
  padding: 140px 120px;
}
</style>